<?php
namespace Admin\Controller;

use Common\Controller\AdminBaseController;

/**
 * 后台登陆控制器
 */
class LoginController extends AdminBaseController
{

    public function _initialize()
    {

    }
    //后台登陆界面
    public function index()
    {

        $admin_id = session('ADMIN_ID');
        //print_r($_COOKIE);exit;
        if (!empty($admin_id)) {
//已经登录
            redirect(U("Admin/index/index"));
        } else {

            if ($_COOKIE['ADMIN_NAME']) {

                $this->assign('ADMIN_NAME', $_COOKIE['ADMIN_NAME']);
                $this->assign('ADMIN_PWD', $_COOKIE['ADMIN_PWD']);
            }
            $this->display();
        }
    }

    public function logout()
    {
        session('ADMIN_ID', null);
        session('ADMIN_NAME', null);
        redirect(U('Admin/Login/index'));
    }

    public function dologin()
    {

        // 做一个简单的登录 组合where数组条件
        $map['username'] = I('post.username');
        $map['password'] = md5(I('post.password'));
        $remember        = I('post.remember');

        $data = M('admin_users')->where($map)->find();
        // M('admin_users')->getlastSql();exit;
        // print_r($data);exit;
        if (empty($data)) {
            $this->error('账号或密码错误');
        } else {
            $_SESSION = array(
                'ADMIN_ID'   => $data['id'],
                'ADMIN_NAME' => $data['username'],
            );

            $updata_data['last_login_ip']   = get_client_ip(0, true);
            $updata_data['last_login_time'] = time();

            $condition['id'] = $_SESSION['ADMIN_ID'];

            if ($remember) {
                cookie("ADMIN_NAME", $_SESSION['ADMIN_NAME'], 3600 * 24 * 30);
                cookie("ADMIN_PWD", I('post.password'), 3600 * 24 * 30);
            }

            $result = M('admin_users')->where($condition)->save($updata_data);

            $this->success('登录成功、前往管理后台', U('Admin/Index/index'));
        }
    }

}
